package com.az.jwtcommon.util;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import com.az.miaoapi.dto.UserDto;
import com.az.miaoapi.response.ResponseCode;
import com.az.miaoapi.exception.BaseException;

import java.util.HashMap;
import java.util.Optional;

public class JwtTool {

    public static String createUserToken(UserDto userDto, Long expireMinute, String secret) {
        return JWTUtil.createToken(new HashMap<>() {{
            put("userId", userDto.getUserId());
            put("role", userDto.getRole());
            put(JWTPayload.EXPIRES_AT,
                    expireMinute != null ? System.currentTimeMillis() + expireMinute * 60 * 1000 : null);
        }}, secret.getBytes());
    }

    public static String createUserToken(UserDto userDto, String secret) {
        return createUserToken(userDto, null, secret);
    }

    public static UserDto getUserDtoFromToken(String token, String secret) {
        Optional<String> tokenOptional = Optional.ofNullable(token);
        if (token == null || !JWTUtil.verify(tokenOptional.orElse(""), secret.getBytes())) {
            throw new BaseException(ResponseCode.TOKEN_INVALIDATION);
        }
        try {
            JWT jwt = JWTUtil.parseToken(token);
            JWTValidator validator = JWTValidator.of(jwt);
            validator.validateDate();
            return new UserDto(
                    Long.parseLong(jwt.getPayload("userId").toString()),
                    jwt.getPayload("role").toString());
        } catch (RuntimeException e) {
            throw new BaseException(ResponseCode.TOKEN_INVALIDATION);
        }
    }
    public static Long getUserIdFromToken(String token, String secret) {
        if (token == null || !JWTUtil.verify(token, secret.getBytes())) {
            throw new BaseException(ResponseCode.TOKEN_INVALIDATION);
        }
        try {
            JWT jwt = JWTUtil.parseToken(token);
            JWTValidator validator = JWTValidator.of(jwt);
            validator.validateDate();
            return Long.parseLong(jwt.getPayload("userId").toString());
        } catch (RuntimeException e) {
            throw new BaseException(ResponseCode.TOKEN_INVALIDATION);
        }
    }
}
